#include<iostream>
#include <string>
#include <stack>
#include <ctype.h>

//https://leetcode.cn/problems/basic-calculator/description/
//栈解决，加减乘除
//栈解决，带括号的处理

using namespace std;

class Solution {
public:
    int calculate(string s) {
        stack<int> nums;
        int num = 0;
        char op = '+';

        for (int i = 0; i < s.size(); ++i) {
            if (isdigit(s[i])) {
                num = num * 10 + (s[i] - '0');
            }
            if (i == s.size() - 1 || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
                if (op == '+') {
                    nums.push(num);
                } else if (op == '-') {
                    nums.push(-num);
                } else if (op == '*') {
                    int temp = nums.top() * num;
                    nums.pop();
                    nums.push(temp);
                } else if (op == '/') {
                    int temp = nums.top() / num;
                    nums.pop();
                    nums.push(temp);
                }
                op = s[i];
                num = 0;
            }
        }

        int result = 0;
        while (!nums.empty()) {
            result += nums.top();
            nums.pop();
        }
        return result;
    }
};


class Solution {
public:
    int calculate(string s) {
        stack<char> st; // 存储正负号
        int ans = 0, num = 0, op = 1;
        st.push(op);

        for (char c : s) {
            if (c == ' ') continue;
            else if (c >= '0') num = num * 10 - '0' + c;
            else {
                ans += op * num;
                num = 0;

                if (c == '+') op = st.top();
                else if (c == '-') op = -st.top();
                else if (c == '(') st.push(op); // 将括号前符号放入栈顶
                else st.pop();
            }
        }

        return ans + op * num;
    }
};
